package com.siyu.quartz.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siyu.basedata.iothlpoint.domain.IotHLPoint;
import com.siyu.basedata.iothlpoint.service.IIotHLPointService;
import com.siyu.basedata.pptnrfuture.domain.PptnRFuture;
import com.siyu.basedata.pptnrfuture.service.IPptnRFutureService;
import com.siyu.common.utils.uuid.IdUtils;
import com.siyu.predict.rsvrjob.domain.RsvrJob;
import com.siyu.predict.rsvrjob.service.IRsvrJobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

@Component("initDataTask")
public class InitDataTask {
    @Autowired
    private IPptnRFutureService pptnRFutureService;
    @Autowired
    private IIotHLPointService iIotHLPointService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IRsvrJobService rsvrJobService;

    /**
     * 预报降雨入库
     *
     * @throws Exception
     */
    @Transactional
    public void initPrData() throws Exception {
//        String[] rscds = new String[]{"43060030012-A4", "43060030017-A4", "43060030011-A4", "43060030014-A4"};
        List<RsvrJob> rsvrJobs = rsvrJobService.list(new LambdaQueryWrapper<RsvrJob>().eq(RsvrJob::getRemark, "initpr"));
        try {
            ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
            // 尝试设置锁，并设置过期时间为60秒
            Boolean lock = ops.setIfAbsent("initPrData", "initPrDatalock", Duration.ofSeconds(600));
            if (lock != null && lock) {
                for (RsvrJob rsvrJob : rsvrJobs) {
                    List<IotHLPoint> list = iIotHLPointService.lambdaQuery().eq(IotHLPoint::getRscd, rsvrJob.getRscd()).eq(IotHLPoint::getSttp, "3").list();
                    for (IotHLPoint iotHLPoint : list) {
                        String url = "https://api.caiyunapi.com/v2.6/i7tXehBFkqTfZUae/" + iotHLPoint.getEslg() + "," + iotHLPoint.getNrlt() + "/hourly?hourlysteps=96";
                        // 发送请求
                        String response = HttpRequest.get(url).execute().body();
                        // 解析JSON响应
                        JSONObject jsonObject = new JSONObject(response);
                        JSONArray precipitationArray = jsonObject.getJSONObject("result").getJSONObject("hourly").getJSONArray("precipitation");
                        // 循环处理precipitation数组
                        List<PptnRFuture> pptnRFutures = new ArrayList<>();
                        for (int i = 0; i < precipitationArray.size(); i++) {
                            JSONObject precipitationObject = precipitationArray.getJSONObject(i);
                            String datetime = precipitationObject.getStr("datetime");
                            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmXXX");
                            String tm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(inputFormat.parse(datetime));
                            Double drp = precipitationObject.getDouble("value");
                            PptnRFuture pptnRFuture = new PptnRFuture();
                            pptnRFuture.setId(IdUtils.getId());
                            pptnRFuture.setTm(DateUtil.parse(tm));
                            pptnRFuture.setDrp(drp);
                            pptnRFuture.setStcd(iotHLPoint.getStcd());
                            pptnRFutures.add(pptnRFuture);
                        }
                        QueryWrapper<PptnRFuture> pptnRFutureQueryWrapper = new QueryWrapper<>();
                        pptnRFutureQueryWrapper.eq("stcd", iotHLPoint.getStcd()).ge("tm", pptnRFutures.get(0).getTm())
                                .le("tm", pptnRFutures.get(pptnRFutures.size() - 1).getTm());
                        pptnRFutureService.remove(pptnRFutureQueryWrapper);
                        pptnRFutureService.saveBatch(pptnRFutures);
                    }
                }
//                stringRedisTemplate.delete("initPrData");
            }
        } catch (Exception e) {
//            stringRedisTemplate.delete("initPrData");
            throw new RuntimeException(e);
        }


    }
}
